#!/usr/bin/env python3
"""
RedFire系统 - 综合服务测试脚本
测试所有服务的导入、启动和基本功能
"""
import sys
import time
import asyncio
import importlib.util
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, List, Tuple
import traceback
import json

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

class ServiceTester:
    """服务测试器"""
    
    def __init__(self):
        self.results = {}
        self.project_root = project_root
        self.services = {
            'user_service': 'backend/services/user_service',
            'api_gateway': 'backend/services/api-gateway', 
            'market_data_service': 'backend/services/market_data_service',
            'trading_service': 'backend/services/trading-service',
            'monitoring_service': 'backend/services/monitoring-service',
            'notification_service': 'backend/services/notification-service'
        }
    
    def print_header(self, title: str):
        """打印测试标题"""
        print(f"\n{'='*60}")
        print(f"🔍 {title}")
        print(f"{'='*60}")
    
    def print_step(self, step: str):
        """打印测试步骤"""
        print(f"\n📋 {step}")
        print("-" * 40)
    
    def test_service_import(self, service_name: str, service_path: str) -> Dict[str, Any]:
        """测试服务导入"""
        result = {
            'service': service_name,
            'import_success': False,
            'app_created': False,
            'main_py_exists': False,
            'error': None,
            'mode': 'unknown',
            'execution_time': 0
        }
        
        start_time = time.time()
        
        try:
            # 检查main.py是否存在
            main_py_path = self.project_root / service_path / 'main.py'
            result['main_py_exists'] = main_py_path.exists()
            
            if not result['main_py_exists']:
                result['error'] = f"main.py not found at {main_py_path}"
                return result
            
            # 尝试导入
            spec = importlib.util.spec_from_file_location(
                f"{service_name}_main", 
                main_py_path
            )
            module = importlib.util.module_from_spec(spec)
            
            # 执行模块
            spec.loader.exec_module(module)
            result['import_success'] = True
            
            # 尝试获取app对象
            if hasattr(module, 'app'):
                app = module.app
                result['app_created'] = True
                
                # 检测运行模式
                if hasattr(app, 'title'):
                    if 'fallback' in app.title.lower():
                        result['mode'] = 'fallback'
                    else:
                        result['mode'] = 'full'
                else:
                    result['mode'] = 'custom'
            
        except Exception as e:
            result['error'] = str(e)
            result['traceback'] = traceback.format_exc()
        
        result['execution_time'] = time.time() - start_time
        return result
    
    def test_all_services(self) -> Dict[str, Any]:
        """测试所有服务"""
        self.print_header("服务导入和启动测试")
        
        all_results = {}
        
        for service_name, service_path in self.services.items():
            self.print_step(f"测试 {service_name}")
            
            result = self.test_service_import(service_name, service_path)
            all_results[service_name] = result
            
            # 输出结果
            if result['import_success']:
                mode_icon = "🟢" if result['mode'] == 'full' else "🟡" if result['mode'] == 'fallback' else "🔵"
                print(f"   {mode_icon} 导入成功 - 模式: {result['mode']}")
                if result['app_created']:
                    print(f"   ✅ FastAPI应用创建成功")
            else:
                print(f"   ❌ 导入失败: {result['error']}")
            
            print(f"   ⏱️ 耗时: {result['execution_time']:.2f}秒")
        
        return all_results
    
    def test_basic_health_endpoints(self) -> Dict[str, Any]:
        """测试基本健康检查端点"""
        self.print_header("健康检查端点测试")
        
        # 这里可以添加实际的HTTP请求测试
        # 由于我们没有运行的服务器，暂时跳过
        print("⏭️ 跳过HTTP端点测试 (需要运行中的服务)")
        return {}
    
    def generate_report(self, results: Dict[str, Any]) -> str:
        """生成测试报告"""
        report = []
        report.append("RedFire系统服务测试报告")
        report.append("=" * 50)
        report.append(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        report.append("")
        
        # 统计信息
        total_services = len(results)
        successful_imports = sum(1 for r in results.values() if r['import_success'])
        full_mode_count = sum(1 for r in results.values() if r['mode'] == 'full')
        fallback_mode_count = sum(1 for r in results.values() if r['mode'] == 'fallback')
        
        report.append("📊 测试统计:")
        report.append(f"   总服务数: {total_services}")
        report.append(f"   成功导入: {successful_imports}")
        report.append(f"   完整模式: {full_mode_count}")
        report.append(f"   降级模式: {fallback_mode_count}")
        report.append(f"   失败数量: {total_services - successful_imports}")
        report.append("")
        
        # 详细结果
        report.append("📋 详细结果:")
        for service_name, result in results.items():
            status = "✅" if result['import_success'] else "❌"
            mode_info = f" ({result['mode']})" if result['import_success'] else ""
            report.append(f"   {status} {service_name}{mode_info}")
            if result['error']:
                report.append(f"      错误: {result['error']}")
        
        return "\n".join(report)
    
    def save_detailed_results(self, results: Dict[str, Any], filename: str = "service_test_results.json"):
        """保存详细测试结果到JSON文件"""
        output_path = self.project_root / "tests" / filename
        
        # 创建输出目录
        output_path.parent.mkdir(exist_ok=True)
        
        # 准备数据（移除不能序列化的内容）
        clean_results = {}
        for service_name, result in results.items():
            clean_result = result.copy()
            # 移除traceback（太长）
            if 'traceback' in clean_result:
                del clean_result['traceback']
            clean_results[service_name] = clean_result
        
        # 添加元数据
        output_data = {
            'test_metadata': {
                'timestamp': datetime.now().isoformat(),
                'project_root': str(self.project_root),
                'total_services': len(results)
            },
            'results': clean_results
        }
        
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(output_data, f, indent=2, ensure_ascii=False)
        
        print(f"\n💾 详细结果已保存到: {output_path}")
    
    def run_comprehensive_test(self):
        """运行综合测试"""
        print("🚀 开始RedFire系统综合测试")
        print(f"📁 项目根目录: {self.project_root}")
        
        # 1. 服务导入测试
        service_results = self.test_all_services()
        
        # 2. 健康检查测试
        health_results = self.test_basic_health_endpoints()
        
        # 3. 生成报告
        self.print_header("测试报告")
        report = self.generate_report(service_results)
        print(report)
        
        # 4. 保存详细结果
        self.save_detailed_results(service_results)
        
        # 5. 总结
        successful_count = sum(1 for r in service_results.values() if r['import_success'])
        total_count = len(service_results)
        
        if successful_count == total_count:
            print(f"\n🎉 所有 {total_count} 个服务测试通过！")
        else:
            print(f"\n⚠️ {successful_count}/{total_count} 个服务测试通过")
        
        return service_results

def main():
    """主函数"""
    tester = ServiceTester()
    results = tester.run_comprehensive_test()
    
    # 返回退出码
    failed_count = sum(1 for r in results.values() if not r['import_success'])
    return failed_count

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)
